﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace LeadChina.AssemblyLine.Common.UDP
{
    public class UDPTool
    {
        private Socket udp = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        private EndPoint targetEP = new IPEndPoint(IPAddress.Any, 0);

        public string IPAddr { get; set; }
        public int RecvLength { get; set;}

        public UDPTool(IPEndPoint ipe)
        {
            udp.Bind(ipe);
            udp.ReceiveTimeout = 100;
            udp.SendTimeout = 100;
        }

        ~UDPTool()
        {
            udp.Dispose();
        }

        public void Send(byte[] msg, IPEndPoint targetIPE)
        {
            udp.SendTo(msg, targetIPE);
        }

        public byte[] Receive()
        {
            RecvLength = 0;
            byte[] buffer = new byte[50];
            try
            {
                RecvLength = udp.ReceiveFrom(buffer, ref targetEP);
                IPAddr = targetEP.ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return buffer;
        }

     


    }
}
